import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_deer/database/beans/employee_list.dart';
import 'package:flutter_deer/database/beans/pay_type_model.dart';
import 'package:flutter_deer/res/colors.dart';
import 'package:flutter_deer/ui/cashier/dialog/selectable_list_dialog.dart';
import 'package:flutter_deer/ui/cashier/provider/cashier_page_provider.dart';
import 'package:flutter_deer/ui/setting/setting_item_data.dart';
import 'package:flutter_deer/ui/setting/setting_page3_link_select.dart';
import 'package:flutter_deer/util/print/print_manager.dart';
import 'package:flutter_deer/util/speak/tts_manger.dart';
import 'package:flutter_deer/util/user_config_manager.dart';
import 'package:get/get.dart';


class SettingPage3Print extends StatefulWidget {
  const SettingPage3Print({super.key});

  @override
  State<SettingPage3Print> createState() => _SettingPage3PrintState();
}

class _SettingPage3PrintState extends State<SettingPage3Print> {
  int _selectedPageIndex = 0; // 当前选中的菜单索引
  final _mPrinter = Get.find<PrintEngineManager>();
  final mProvider = Get.find<CashierPageProvider>();

  // 右侧内容区域根据选中菜单显示不同内容
  Widget _buildContent() {
    switch (_selectedPageIndex) {
      case 0:
        return const Center(child: Text('打印总开关'));
      case 1:
        return _buildSourceSelectionPage();
      case 2:
        return _buildEmployeeSelectionPage();
      case 3:
        return _buildGunNumberSelectionPage();
      case 4:
        return _buildPayTypeSelectionPage();
      case 5:
        return const SettingPage3LinkSelect();
      default:
        return const Center(child: Text('零管配置'));
    }
  }

  // 构建按来源
  Widget _buildSourceSelectionPage() {
    // 多选列表对话框
    return SelectableListDialog<BroadcastType>(
      title: '请选来源',
      items: BroadcastType.values,
      selectionMode: SelectionMode.multiple,
      selectedItems: _mPrinter.openPrintByClientSelect,
      itemBuilder: (e) => e.label,
      itemCompare: (a, b) => a.indexKey == b.indexKey,
      onConfirmed: (selectedItems) {
        print('selectedItems:$selectedItems');
        _mPrinter.isOpenPrintByClient = selectedItems.map((e) => e.indexKey.toString()).toList();
        setState(() => _selectedPageIndex = 0);
      },
      onCancel: () {
        setState(() => _selectedPageIndex = 0);
      },
    );
  }

  // 构建按员工选择页面
  Widget _buildEmployeeSelectionPage() {
    final list = <EmployeeEntity>[];
    for (final element in mProvider.mAllListEmployee) {
      if (_mPrinter.rxIsOpenPrintByEmployee.contains(element.userId.toString())) {
        list.add(element);
      }
    }
    // 多选列表对话框
    return SelectableListDialog<EmployeeEntity>(
      title: '请选择员工',
      items: mProvider.mAllListEmployee,
      selectionMode: SelectionMode.multiple,
      selectedItems: list,
      itemBuilder: (employee) => employee.userName,
      itemCompare: (a, b) => a.userId == b.userId,
      onConfirmed: (selectedItems) {
        print('selectedItems:$selectedItems');
        _mPrinter.isOpenPrintByEmployee = selectedItems.map((e) => e.userId).toList();
        setState(() => _selectedPageIndex = 0);
      },
      onCancel: () {
        setState(() => _selectedPageIndex = 0);
      },
    );
  }

  // 构建枪号选择页面
  Widget _buildGunNumberSelectionPage() {
    final List<String> _gunList = [];
    UserConfigManager.getOilGuns().forEach((oils) {
      oils.shelfList?.forEach((shelf) {
        _gunList.add('${shelf.shelfNo}');
      });
    });
    _gunList.sort((a, b) {
      return int.parse(a).compareTo(int.parse(b));
    });

    // 多选列表对话框
    return SelectableListDialog<String>(
      title: '请选择枪号',
      items: _gunList,
      selectionMode: SelectionMode.multiple,
      selectedItems: _mPrinter.rxIsOpenPrintByGun,
      itemBuilder: (nzl) => nzl.toString(),
      itemCompare: (a, b) => a == b,
      onConfirmed: (selectedItems) {
        print('selectedItems:$selectedItems');
        _mPrinter.isOpenPrintByGun = selectedItems;
        setState(() => _selectedPageIndex = 0);
      },
      onCancel: () {
        setState(() => _selectedPageIndex = 0);
      },
    );
  }

  // 构建支付方式选择页面
  Widget _buildPayTypeSelectionPage() {
    final list = <PayTypeModel>[];
    for (final element in mProvider.mALlListPayType) {
      if (_mPrinter.rxIsOpenPrintByPayType.contains(element.paymentModeId)) {
        list.add(element);
      }
    }
    return SelectableListDialog<PayTypeModel>(
      title: '请选择支付方式',
      items: mProvider.mALlListPayType,
      selectionMode: SelectionMode.multiple,
      selectedItems: list,
      itemBuilder: (payType) => payType.paymentName,
      itemCompare: (a, b) => a.paymentModeId == b.paymentModeId,
      onConfirmed: (selectedItems) {
        print('selectedItems:$selectedItems');
        _mPrinter.isOpenPrintByPayType = selectedItems.map((e) => e.paymentModeId).toList();
        setState(
          () => _selectedPageIndex = 0,
        );
      },
      onCancel: () {
        setState(
          () => _selectedPageIndex = 0,
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    // 平板布局 - 左右分栏
    return Scaffold(
      body: Obx(() => Row(
            children: [
              // 左侧菜单区域
              Container(
                width: 380,
                color: Colours.bg_color,
                padding: const EdgeInsets.only(top: 8.0, bottom: 8.0, left: 0.0, right: 8.0),
                child: ListView(
                  children: <Widget>[
                    // 语音打印总开关
                    _buildSettingGroup([
                      SettingItemData(
                        title: '打印总开关',
                        trailing: CupertinoSwitch(
                          value: _mPrinter.rxIsOpenPrint.value,
                          onChanged: (v) => setState(
                            () => _mPrinter.isOpenPrint = v,
                          ),
                          activeColor: CupertinoColors.activeBlue, // 开启颜色
                          trackColor: CupertinoColors.systemGrey4, // 关闭颜色
                        ),
                        showArrow: false,
                        onTap: () => setState(() => _selectedPageIndex = 0),
                      ),
                    ]),
                    const SizedBox(height: 8),

                    // 语音打印和打印控制组合项
                    _buildSettingGroup([
                      SettingItemData(
                        title: '按来源打印',
                        trailing: Text(_mPrinter.openPrintByClientString, style: const TextStyle(fontSize: 12, color: Colors.grey)),
                        showArrow: true,
                        onTap: () => setState(() => _selectedPageIndex = 1),
                      ),
                      SettingItemData(
                        title: '按员工打印',
                        trailing: Text(selectOpenPrintByEmployeeString, style: const TextStyle(fontSize: 12, color: Colors.grey)),
                        showArrow: true,
                        onTap: () => setState(() => _selectedPageIndex = 2),
                      ),
                      SettingItemData(
                        title: '按枪号打印',
                        trailing: Text(selectOpenPrintByGunString, style: const TextStyle(fontSize: 12, color: Colors.grey)),
                        showArrow: true,
                        onTap: () => setState(() => _selectedPageIndex = 3),
                      ),
                      SettingItemData(
                        title: '按支付方式打印',
                        trailing: Text(selectOpenPrintByPayTypeString, style: const TextStyle(fontSize: 12, color: Colors.grey)),
                        showArrow: true,
                        onTap: () => setState(() => _selectedPageIndex = 4),
                      ),
                      SettingItemData(
                        title: '按业务类型打印',
                        trailing: const Text('(小票联数) ', style: TextStyle(fontSize: 16, color: Colors.grey)),
                        showArrow: true,
                        onTap: () => setState(() => _selectedPageIndex = 5),
                      ),
                    ]),
                    // PressBlueButton(text: '重新登录', height: 40, fontSize: 18, onPressed: () => _showExitDialog()),
                  ],
                ),
              ),
              // 右侧内容区域
              Expanded(child: _buildContent()),
            ],
          )),
    );
  }

  // 构建设置项组
  Widget _buildSettingGroup(List<SettingItemData> items) {
    return Material(
      color: Colors.white,
      borderRadius: BorderRadius.circular(3),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: items.map((item) {
          final int index = items.indexOf(item);
          final bool isSelected = ((index + 1) == _selectedPageIndex) && items.length > 1;
          return Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Material(
                  color: isSelected ? Theme.of(context).primaryColor.withOpacity(0.1) : Colors.transparent,
                  child: InkWell(
                    // hoverColor: Colours.bg_press,
                    onTap: item.onTap,
                    child: Container(
                      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                      child: Row(
                        children: [
                          Expanded(
                            child: Text(item.title, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold, color: Colors.black87)),
                          ),
                          if (item.trailing != null) item.trailing!,
                          if (item.showArrow) const Icon(Icons.arrow_forward_ios, color: Colors.grey, size: 14),
                        ],
                      ),
                    ),
                  )),
              if (index < items.length - 1) const Divider(height: 1, thickness: 1, indent: 16, endIndent: 16),
            ],
          );
        }).toList(),
      ),
    );
  }

  // 按员工打印选择弹窗
  String get selectOpenPrintByEmployeeString {
    final list = _mPrinter.rxIsOpenPrintByEmployee;
    if (list.isEmpty) {
      return '关闭';
    } else if (list.length == mProvider.mAllListEmployee.length) {
      return '全部';
    } else {
      return '${list.length}/${mProvider.mAllListEmployee.length}';
    }
  }

  // 按枪号打印选择弹窗
  String get selectOpenPrintByGunString {
    final List<int> gunList = [];
    UserConfigManager.getOilGuns().forEach((oils) {
      oils.shelfList?.forEach((shelf) {
        gunList.add(shelf.shelfNo!);
      });
    });
    gunList.sort((a, b) {
      return a.compareTo(b);
    });

    final list = _mPrinter.rxIsOpenPrintByGun;
    if (list.isEmpty) {
      return '关闭';
    } else if (list.length == gunList.length) {
      return '全部';
    } else {
      return '${list.length}/${gunList.length}';
    }
  }

  // 按支付方式打印选择弹窗
  String get selectOpenPrintByPayTypeString {
    if (_mPrinter.rxIsOpenPrintByPayType.isEmpty) {
      return '关闭';
    } else if (_mPrinter.rxIsOpenPrintByPayType.length == mProvider.mALlListPayType.length) {
      return '全部';
    } else {
      return '${_mPrinter.rxIsOpenPrintByPayType.length}/${mProvider.mALlListPayType.length}';
    }
  }
}
